<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="3" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="auto"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!-- <ContentWrap> -->
      <Table
        :columns="columns"
        :page-param="queryParams"
        :page-data="userData"
        @page-change="getList"
        adaptive
        height-per="90"
        save-key="user"
      >
        <template #menu="{ row }">
          <context-menu-item
            label="修改"
            @click="openForm('update', row.id)"
            v-hasPermi="['system:user:update']"
          />
          <context-menu-item
            label="删除"
            @click="handleDelete(row.id)"
            v-hasPermi="['system:user:delete']"
          />
          <context-menu-item
            label="重置密码"
            @click="handleResetPwd(row)"
            v-hasPermi="['system:user:update-password']"
          />
          <context-menu-item
            label="分配角色"
            @click="handleRole(row)"
            v-hasPermi="['system:permission:assign-user-role']"
          />
        </template>
        <template #status="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(row)"
          />
        </template>
      </Table>
    </el-col>
  </el-row>

  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <Import
    ref="importFormRef"
    @success="getList"
    :template-method="UserApi.getImportTemplate"
    :import-method="UserApi.importExcel"
    title="用户导入"
  />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
</template>
<script setup lang="ts" name="SystemUser">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
// import download from '@/utils/download'
import * as UserApi from '@/api/system/user/user'
import UserForm from './UserForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import DeptTree from './DeptTree.vue'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
import { CommonStatusEnum } from '@/utils/constants'
const loading = ref(true) // 列表的加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined,
  deptId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const columns: TableColumnList = [
  {
    label: '用户名称',
    prop: 'username',
    showOverflowTooltip: true
  },
  {
    label: '用户昵称',
    prop: 'nickname',
    showOverflowTooltip: true
  },

  {
    label: '部门',
    prop: 'dept.name',
    showOverflowTooltip: true
  },
  {
    label: '手机号码',
    prop: 'mobile'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '职位',
    prop: 'position'
  },
  {
    label: '状态',
    prop: 'status',
    slot: 'status'
  },
  {
    label: '创建时间',
    prop: 'createTime',
    formatter: ({ createTime }) => formatDate(createTime)
  }
]

const userData = ref()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    userData.value = await UserApi.page(queryParams)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要' + text + '"' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateStatus({ id: row.id, status: row.status })
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLED : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
// const exportLoading = ref(false)
// const handleExport = async () => {
//   try {
//     // 导出的二次确认
//     await message.exportConfirm()
//     // 发起导出
//     exportLoading.value = true
//     const data = await UserApi.exported(queryParams)
//     download.excel(data, '用户数据.xls')
//   } catch {
//   } finally {
//     exportLoading.value = false
//   }
// }

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleted(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.updatePassword({ id: row.id, password: password })
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
